package com.xi.controller;

import com.xi.pojo.*;
import com.xi.service.FineService;
import com.xi.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    public Integer overdueCount = 0;//逾期次数

    public Integer id;//记录当前用户登录的id

    @Autowired
    private UserService userService;

    @Autowired
    private FineService fineService;

    /*
     * 用户的分页查询
     * */
    @GetMapping
    public Result page(UserQueryParam userQueryParam) {
        log.info("用户分页查询 , {}", userQueryParam);
        PageResult pageResult = userService.page(userQueryParam);
        return Result.success(pageResult);
    }

    /*
    * 用户删除,根据id进行删除
    * */
    @DeleteMapping
    public Result deleteById(Integer id) {
        log.info("用户删除 , {}", id);
        userService.deleteById(id);
        return Result.success();
    }

    //查询所有图书
    @GetMapping("/book")
    public Result pageSearchBook(UserBookQueryParam userBookQueryParam){
        log.info("分页查询图书:{}", userBookQueryParam);
        try {
            PageResult<Book> pageResult = userService.page(userBookQueryParam);
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询图书异常", e);
            return Result.error("查询失败，请稍后再试");
        }
    }

    @PostMapping
    public Result addUser(@RequestBody User user){
        log.info("添加用户:{}", user);
        try {
            userService.addUser(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error("注册失败，请稍后再试");
        }
    }
    // 检查用户名是否存在
    @GetMapping("/exists")
    public Result checkUserExists(String username) {
        boolean exists = userService.checkUserExists(username);
        return Result.success(exists);
    }

    /**
     * 用户查询借阅图书
     */
    @GetMapping("/borrow/list")
    public Result searchBorrowBook(HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error("未登录");
        }

        User user = userService.getCurrentUser(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        List<Borrowable> borrowList = userService.searchBorrowBookByUserId(user.getId());
        return Result.success(borrowList);
    }


    // 获取当前登录用户信息
    @GetMapping("/information")
    public Result getCurrentUser(HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error("未登录");
        }

        User user = userService.getCurrentUser(username);

        if (user == null) {
            return Result.error("用户不存在");
        }

        // 获取总罚款金额
        Double totalFine = fineService.getTotalFinesByUserId(user.getId());
        user.setFineAmount(totalFine); // 用户对象中增加 fineAmount 字段

        log.info("获取当前用户: {}", user);
        return Result.success(user);
    }



    /**
     * 用户借阅图书
     */
    @PostMapping("/borrow")
    public Result borrowBook(@RequestParam("bookId") Integer bookId, HttpSession session) {
        log.info("用户借阅图书: bookId={}", bookId);
        try {
            // 从 Session 中获取当前登录用户名
            String username = (String) session.getAttribute("username");
            if (username == null) {
                return Result.error("未登录");
            }

            // 查询用户信息获取 userId
            User user = userService.getCurrentUser(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Integer userId = user.getId();

            // 调用借阅服务
            boolean success = userService.borrowBook(userId, bookId);
            if (success) {
                return Result.success("借阅成功");
            } else {
                return Result.error("借阅失败，图书可能不可用");
            }
        } catch (Exception e) {
            log.error("借阅图书异常", e);
            return Result.error("系统异常，请稍后再试");
        }
    }

    /**
     * 用户归还图书
     */
    @DeleteMapping("/borrow")
    public Result returnBook(@RequestParam("bookId") Integer bookId, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error("未登录");
        }

        User user = userService.getCurrentUser(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        Borrow borrowRecord = userService.getBorrowRecord(user.getId(), bookId);
        boolean success = userService.returnBook(user.getId(), bookId);

        if (success && borrowRecord != null) {
            fineService.calculateAndApplyFine(borrowRecord); // 计算罚款
        }

        // 判断是否逾期，并更新计数器
        assert borrowRecord != null;
        if (LocalDateTime.now().isAfter(borrowRecord.getReturnTime())) {
            overdueCount = overdueCount + 1;  // 逾期则计数 +1
        }

        if (success) {
            return Result.success("归还成功");
        } else {
            return Result.error("归还失败，请确认图书是否已被归还");
        }
    }


    /**
     * 用户续借图书
     */
    @PutMapping("/borrow/renew")
    public Result renewBook(@RequestParam("bookId") Integer bookId, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error("未登录");
        }

        User user = userService.getCurrentUser(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        boolean success = userService.renewBook(user.getId(), bookId);
        if (success) {
            return Result.success("续借成功");
        } else {
            return Result.error("续借失败");
        }
    }

    @PostMapping("/reservation")
    public Result handleReserveBook(@RequestBody Map<String, Integer> payload, HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error("未登录");
        }

        User user = userService.getCurrentUser(username);
        if (user == null) {
            return Result.error("用户不存在");
        }

        Integer bookId = payload.get("bookId");

        boolean success = userService.reserveBook(user.getId(), bookId, user.getUsername());
        if (success) {
            return Result.success("预约成功");
        } else {
            return Result.error("该书不可预约或已预约");
        }
    }

    @GetMapping("/reservation/list")
    public Result getMyReservations(HttpSession session) {
        String username = (String) session.getAttribute("username");
        if (username == null) {
            return Result.error("未登录");
        }

        User user = userService.getCurrentUser(username);
        List<Reservation> reservations = userService.getReservationsByUserId(user.getId());
        return Result.success(reservations);
    }

    @DeleteMapping("/reservation/{id}")
    public Result cancelReservation(@PathVariable("id") Integer id, HttpSession session) {
        try {
            String username = (String) session.getAttribute("username");
            if (username == null) {
                return Result.error("未登录");
            }

            boolean success = userService.cancelReservation(id);
            if (success) {
                return Result.success("取消成功");
            } else {
                return Result.error("取消失败或预约不存在");
            }
        } catch (Exception e) {
            log.error("取消预约接口异常", e);
            return Result.error("服务器内部错误，请稍后再试");
        }
    }

    @PutMapping
    public Result updateUserInfo(@RequestBody Map<String, String> payload, HttpSession session) {
        String currentUsername = (String) session.getAttribute("username");
        if (currentUsername == null) {
            return Result.error("未登录");
        }

        String oldUsername = payload.get("oldUsername");
        String newUsername = payload.get("newUsername");
        String realName = payload.get("realName");
        String phone = payload.get("phone");

        if (!currentUsername.equals(oldUsername)) {
            return Result.error("无权限操作");
        }

        if (newUsername == null || realName == null || phone == null) {
            return Result.error("参数缺失");
        }

        try {
            boolean success = userService.updateUserInfo(oldUsername, newUsername, realName, phone);

            if (success) {
                // 更新 session 中的 username
                session.setAttribute("username", newUsername);
                return Result.success("修改成功");
            } else {
                return Result.error("修改失败");
            }
        } catch (Exception e) {
            log.error("修改用户信息失败", e);
            return Result.error("系统异常");
        }
    }

    @PutMapping("/password")
    public Result changePassword(@RequestBody Map<String, String> payload, HttpSession session) {
        String currentUsername = (String) session.getAttribute("username");
        if (currentUsername == null) {
            return Result.error("未登录");
        }

        String username = payload.get("username");
        String oldPassword = payload.get("oldPassword");
        String newPassword = payload.get("newPassword");

        if (!currentUsername.equals(username)) {
            return Result.error("无权限操作");
        }

        try {
            boolean success = userService.changePassword(username, oldPassword, newPassword);
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("密码修改失败");
            }
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error("系统异常");
        }
    }
}
